package org.light4admin.modules.system.controller;

import org.light4admin.common.base.BaseController;
import org.light4admin.common.Constants;
import org.light4admin.common.aop.auth.PreAuthorize;
import org.light4admin.common.base.PageResponse;
import org.light4admin.common.base.Response;
import org.light4admin.modules.system.domain.SysLogininfor;
import org.light4admin.modules.system.service.ISysLogininforService;
import org.light4admin.util.IpUtils;
import org.light4admin.util.ServletUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 系统访问记录
 *
 * @author light4admin
 */
@RestController
@RequestMapping("/logininfor")
public class SysLogininforController extends BaseController {
    @Autowired
    private ISysLogininforService logininforService;

    @PreAuthorize(hasPermi = "system:logininfor:list")
    @GetMapping("/list")
    public PageResponse list(SysLogininfor logininfor) {
        startPage();
        List<SysLogininfor> list = logininforService.selectLogininforList(logininfor);
        return getDataTable(list);
    }


    @PreAuthorize(hasPermi = "system:logininfor:remove")
    @DeleteMapping("/{infoIds}")
    public Response<Void> remove(@PathVariable Long[] infoIds) {
        logininforService.deleteLogininforByIds(infoIds);
        return Response.success();
    }

    @PreAuthorize(hasPermi = "system:logininfor:remove")
    @DeleteMapping("/clean")
    public Response<Void> clean() {
        logininforService.cleanLogininfor();
        return Response.success();
    }

    @PostMapping
    public Response<Void> add(@RequestParam("username") String username, @RequestParam("status") String status,
                              @RequestParam("message") String message) {
        String ip = IpUtils.getIpAddr(ServletUtils.getRequest());

        // 封装对象
        SysLogininfor logininfor = new SysLogininfor();
        logininfor.setUserName(username);
        logininfor.setIpaddr(ip);
        logininfor.setMsg(message);
        // 日志状态
        if (Constants.LOGIN_SUCCESS.equals(status) || Constants.LOGOUT.equals(status)) {
            logininfor.setStatus("0");
        } else if (Constants.LOGIN_FAIL.equals(status)) {
            logininfor.setStatus("1");
        }
        logininforService.insertLogininfor(logininfor);
        return Response.success();
    }
}
